﻿using ConsoleAppEFcoreTest2.LocalContext;
using ConsoleAppEFcoreTest2.Model;
using System;
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace ConsoleAppEFcoreTest2
{
    class Program
    {
        static void Main(string[] args)
        {
            //AddTestData();
            TestOptimistic();
        }

        private static void TestOptimistic()
        {
            //config 配置中添加并发令牌
            using (MyDbContext context = new MyDbContext())
            {
                House h = new House() { Id = 1 };
                Console.WriteLine("Enter your Name:");
                h.Owner = Console.ReadLine();
                context.Houses.Update(h);
                try
                {
                    context.SaveChanges();
                    Console.WriteLine($"{h.Owner} 抢占成功。");
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    var entity = ex.Entries.First();
                    var dbValues = entity.GetDatabaseValues();
                    string owner = dbValues.GetValue<string>("Owner");
                    Console.WriteLine($"{h.Name} 已经被 {owner} 占用。");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"未知错误：{ex.Message}");
                }

            }
        }

        private static void AddTestData()
        {
            using (MyDbContext context = new MyDbContext())
            {
                context.Houses.Add(new Model.House() { Name = "1-20-203" });
                context.Houses.Add(new House() { Name = "1-16-120" });
                context.SaveChanges();
            }
        }
    }
}
